#!/bin/bash

set -e
set -x

# yum install -y --downloadonly --downloaddir=. elasticsearch
bypy download elasticsearch-7.17.26-x86_64.rpm
source ./env.sh

iplist_path=config
i=1
master_node_name="node-1"
while read -r line
do
    case $line in
        *'#'*)
            continue
        ;;
        *'end'*)
            break
        ;;
        *)
            IFS=',' read -ra parts <<< "$line"
        ;;
    esac
    
    pass="${parts[0]}" 
    address="${parts[1]}"
    hostname="${parts[2]}"
    if [ $address ];then
        sshpass -p$pass scp elasticsearch-7.17.26-x86_64.rpm $address:/opt/
        sshpass -p$pass ssh -n $address yum -y --disablerepo='*' localinstall /opt/elasticsearch-7.17.26-x86_64.rpm
        cp elasticsearch.yml.tpl elasticsearch.yml
        sed -i "s/(node_name)/node-$i/g" elasticsearch.yml
        sed -i "s/(master_node_name)/$master_node_name/g" elasticsearch.yml
        sed -i "s/(node_hosts)/$node_hosts/g" elasticsearch.yml
        sshpass -p$pass scp elasticsearch.yml $address:/etc/elasticsearch/elasticsearch.yml
        sshpass -p$pass ssh -n $address chown -R elasticsearch:elasticsearch /etc/elasticsearch
        sshpass -p$pass ssh -n $address chown -R elasticsearch:elasticsearch /usr/share/elasticsearch
        sshpass -p$pass ssh -n $address systemctl daemon-reload
        sshpass -p$pass ssh -n $address systemctl start elasticsearch.service
        let i=i+1
    fi
done < $iplist_path
curl http://127.0.0.1:9200/_cat/nodes
set +x
set +e